package com.foreveross.proxyip.infra.utils;


import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ehcache缓存工具类
 * 
 * @author fb
 */
public class CacheUtils {
	//private final static CacheManager cacheManager = new CacheManager(CacheUtils.class.getResource("/mofangEhcache.xml"));
	private final static CacheManager cacheManager = new CacheManager(CacheUtils.class.getClassLoader().getResource("mofangEhcache.xml"));

	private Logger logger = LoggerFactory.getLogger(CacheUtils.class);

	private Cache cache;

	private CacheUtils() {
		
	}
	
	
	/*
	 * 缓存实例组枚举类
	 */
	public static enum CacheInstance {
		// 系统参数缓存 3分钟失效
		SYSTEM("systemConfig"),
		// 通用缓存 6分钟失效
		MOFANG("mofangWebCache"),
		// 程序自定义分钟失效缓存，不读取xml配制
		CUSTOM("mofangCustom"),
		// 通用永久缓存
		FOREVER("mofangWebForeverCache");

		CacheInstance(String group) {
			this.groupkey = group;
		}

		private final String groupkey;

		public String getGroup() {
			return groupkey;
		}

	};

	/**
	 * 获取缓存对象实例
	 */
	public static CacheUtils newInstance() {
		return new CacheUtils();
	}

	/**
	 * 获取缓存实例, 如果传入的是自定义缓存组而默认时间5分钟
	 * 
	 * @param group
	 *            缓存组id
	 * 
	 * @return Cache cache实例对象
	 */
	public CacheUtils instanceCache(CacheInstance group) {
		logger.debug("获取缓存group，key:{}", group.getGroup());
		
		if (CacheInstance.CUSTOM == group) {
			customInstanceCache(5);
		} else {
			cache = cacheManager.getCache(group.getGroup());
		}
		
		return this;
	}
	
	/**
	 * 创建自定义缓存实例
	 * 
	 * @param time
	 *            失效时间(单位分钟)
	 * 
	 * @return Cache cache实例对象
	 */
	public synchronized CacheUtils customInstanceCache(int time) {
		logger.debug("获取自定义缓存实例，时间为{}分钟", time);
		cache = cacheManager.getCache(CacheInstance.CUSTOM.groupkey + time);
		
		if (cache == null) {
			logger.debug("创建自定义缓存实例，时间为{}分钟", time);
			cache = new Cache(CacheInstance.CUSTOM.groupkey + time, time, true, false,1800 , time*60);
			cacheManager.addCache(cache);
		}

		return this;
	}
	
	/**
	 * 添加缓存
	 * 
	 * @param key
	 *            缓存键
	 * @param value
	 *            缓存值
	 */
	public <T, K> void put(T key, K value) {
		logger.debug("存放缓存组为：{}，key为：{}，value为：{}缓存！",new Object[]{cache.getName(), key, value});
		
		Element element = new Element(key, value);
		cache.put(element);
	}

	/**
	 * 获取缓存
	 * 
	 * @param key
	 *            缓存键
	 */
	@SuppressWarnings("unchecked")
	public <T,K> K get(T key) {
		Element element = cache.get(key);
		K reult = (K) (element == null ? element : element.getObjectValue());
		
		logger.debug("获取缓存组为：{}，key为：{} 缓存值为：{}", new Object[]{cache.getName(), key, reult});
		
		return  reult;
	}

	/**
	 * 删除缓存
	 * 
	 * @param key
	 *            缓存键
	 */
	public <T> void remove(T key) {
		logger.debug("删除缓存组为：{}，key为：{}缓存！", cache.getName(), key);
		
		cache.remove(key);
	}

	/**
	 * 删除所有缓存
	 */
	public void removeAll() {
		logger.debug("删除缓存组为：{}的所有缓存!", cache.getName());
		
		cache.removeAll();
	}
}
